package com.meilai.project.service.thirdPart.impl;

import com.alibaba.fastjson.JSONObject;
import com.meilai.project.service.thirdPart.TencentLocationService;
import com.meilai.project.util.HttpUtils;
import com.meilai.project.util.Md5Util;
import com.meilai.project.util.SortMapUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author 张驰
 * @date 2021/3/11 16:51
 */
@Service
@Log4j2
public class TencentLocationServiceImpl implements TencentLocationService {
    private final String domain = "https://apis.map.qq.com";

    @Value("${tencent-location-service.key}")
    private String key;

    @Value("${tencent-location-service.secret-key}")
    private String SK;

    @Override
    public JSONObject WSPlaceSearch(String keyword, String boundary, String category) {
        HashMap<String,String> querys = new HashMap<>();
        querys.put("keyword",keyword);
        querys.put("boundary","region("+boundary+")");
        if(StringUtils.isNotEmpty(category)){
            querys.put("filter","category="+category);
        }
        return doGet("/ws/place/v1/search",querys);
    }

    @Override
    public JSONObject WSPlaceSearchPage(String keyword, String boundary, String category, Integer page_index, Integer page_size) {
        HashMap<String,String> querys = new HashMap<>();
        querys.put("keyword",keyword);
        querys.put("boundary","region("+boundary+")");
        if(StringUtils.isNotEmpty(category)){
            querys.put("filter","category="+category);
        }
        querys.put("page_index",page_index.toString());
        querys.put("page_size",page_size.toString());
        return doGet("/ws/place/v1/search",querys);
    }

    @Override
    public JSONObject WSPlaceSearchTradeArea(String keyword, String boundary, String lat, String lng, Integer page_index, Integer page_size) {
        HashMap<String,String> querys = new HashMap<>();
        querys.put("keyword",StringUtils.isEmpty(keyword)?"商业街":keyword);
        querys.put("boundary","region("+boundary+",0,"+lat+","+lng+")");
        querys.put("filter","category=商业步行街");
        querys.put("page_size", page_size.toString());
        querys.put("page_index", page_index.toString());
        return doGet("/ws/place/v1/search",querys);
    }

    @Override
    public JSONObject WSDistrictList() {
        return doGet("/ws/district/v1/list",new HashMap<>());
    }

    @Override
    public JSONObject WSDistrictSearch(String keyword) {
        HashMap<String,String> querys = new HashMap<>();
        querys.put("keyword", keyword);
        querys.put("get_polygon","2");
        querys.put("max_offset","100");
        return doGet("/ws/district/v1/search",querys);
    }

    @Override
    public JSONObject WSGeocoder(BigDecimal lat, BigDecimal lng) {
        HashMap<String,String> querys = new HashMap<>();
        querys.put("location",lat.toPlainString()+","+lng.toPlainString());
        return doGet("/ws/geocoder/v1",querys);
    }

    @Override
    public JSONObject WSIP(String ip) {
        HashMap<String,String> querys = new HashMap<>();
        querys.put("ip",ip);
        return doGet("/ws/location/v1/ip",querys);
    }

    /**
     * 生成sig
     * @param uri 请求路径
     * @param map 请求参数
     */
    private String generateSig(String uri, Map<String, String> map){
        map.put("key",key);
        Map<String, String> sortMap = SortMapUtil.sortMapByKey(map);
        StringBuilder sbUrl = new StringBuilder(uri);
        StringBuilder sbQuery = new StringBuilder();
        for (Map.Entry<String,String> entry:sortMap.entrySet()){
            if (0 < sbQuery.length()) sbQuery.append("&");
            sbQuery.append(entry.getKey()).append("=").append(entry.getValue());
        }
        if (0 < sbQuery.length()) {
            sbUrl.append("?").append(sbQuery);
        }
        sbUrl.append(SK);
        return Md5Util.getMd5(sbUrl.toString());
    }

    private JSONObject doGet(String uri, Map<String, String> querys){
        JSONObject jsonObject = null;

        String sig = generateSig(uri,querys);
        querys.put("sig",sig);

        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        HttpResponse response = null;
        try{
            response = HttpUtils.doGet(domain,uri,headers,querys);
            // 得到返回的参数
            String getResponse = EntityUtils.toString(response.getEntity());
            jsonObject = JSONObject.parseObject(getResponse);
        }catch (Exception e){
            log.error("腾讯位置服务请求失败",e);
        }
        return jsonObject;
    }

    private JSONObject doPost(String uri, JSONObject body) {
        HashMap<String, String> map = new HashMap<>();
        Iterator iter = body.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            map.put(entry.getKey().toString(),entry.getValue().toString());
        }

        JSONObject jsonObject = null;

        String sig = generateSig(uri,map);
        body.put("sig",sig);

        HttpResponse response = null;
        try{
            response = HttpUtils.doPost(domain,uri,null,null,body.toJSONString());
            // 得到返回的参数
            String getResponse = EntityUtils.toString(response.getEntity());
            jsonObject = JSONObject.parseObject(getResponse);
        }catch (Exception e){
            log.error("腾讯位置服务请求失败",e);
        }
        return jsonObject;
    }
}
